<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Http\model\Dictionary;
use App\Http\Comm\CommonController as common;

class BranchController extends BaseController
{
    /**
     * 公司(分支机构)接口
     * by 吉星
     */
    // 公司(分支机构)信息数据
    public function branch(Request $request){
        if($request){
            $where = [];
            $requestsss = $request->all();
            $whereper['branch_name'] = isset($request['branch_name']) ? $request['branch_name'] : '';
            $whereper['area'] = isset($request['area']) ? $request['area'] : '';
            $whereper['type'] = isset($request['type']) ? $request['type'] : '';
            $whereper['starttime'] = isset($request['starttime']) ? $request['starttime'] : '';
            $whereper['endtime'] = isset($request['endtime']) ? $request['endtime'] : '';
            // dump($whereper);
            // dump($requestsss);exit;
            if($request['branch_name']){
                $where['a.company_name'] = $request['branch_name'] ? $request['branch_name'] : '';
            }
            if($request['area']){
                $where['a.area'] = $request['area'] ? $request['area'] : '';
            }
            if ($request['type']) {
                $where['a.type'] = $request['type'] ? $request['type'] : '';
            }
            if ($request['starttime'] || $request['endtime']) {
                $starttime = strtotime($request['starttime']);
                $endtime = strtotime($request['endtime']);
                $data = Db::table('branch as a')
                    ->join('user as u','u.id','=','a.update_user','left')
                    ->where($where)
                    ->where('a.is_delete','=','1')
                    ->whereBetween('a.update_time',[$starttime,$endtime])
                    ->select("a.*",'u.name as adminname')
                    ->get()
                    ->toArray();
            }else{
                $data = Db::table('branch as a')
                    ->join('user as u','u.id','=','a.update_user','left')
                    ->where($where)
                    ->where('a.is_delete','=','1')
                    ->select("a.*",'u.name as adminname')
                    ->get()
                    ->toArray();
                    // dump(1111);
            }
            $data = json_decode(json_encode($data),true);
            foreach ($data as $key => $value) {
                if($value['area']){
                    $area = Db::table("region")
                        ->where('code',$value['area'])
                        ->first();
                    $area =  json_decode(json_encode($area),true);
                    $paranarea = Db::table('region')
                        ->where('code',$area['parentCode'])
                        ->first();
                    $paranarea =  json_decode(json_encode($paranarea),true);
                    $paranareas = Db::table('region')
                        ->where('code',$paranarea['parentCode'])
                        ->first();
                    $paranareas =  json_decode(json_encode($paranareas),true);
                    $data[$key]['areaname'] = $paranareas['fullName'].$paranarea['fullName'].$area['fullName'];
                }
            }
            // echo "<pre>";
            // print_r($data);exit;
            if($data){
                $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$data,'where'=>$whereper];
            }else{
                $res = ['code'=>1002,'message'=>'没有找到符合条件的数据!','where'=>$whereper];
            }
        }else{
            $res = ['code'=>1001,'message'=>'参数错误!'];
        }
        
        return $res;
    }
    //修改公司信息页面赋值
    public function edit(Request $request){
        if($request['id']){
            $data = Db::table('branch as b')
                ->join('branch_user as u','b.id','=','u.branch_id','left')
                ->where('b.id',$request['id'])
                ->first();
        $data = json_decode(json_encode($data),true);
        $zidian = new Dictionary();
        $yewuxian = $zidian->contents("1"); //传入对应的字段值
        $jigouleixing = ['自营','合作','外卖'];
            return ['data'=>$data,'code'=>1000,'message'=>'获取数据成功','yewuxian'=>$yewuxian,'jigouleixing'=>$jigouleixing];
        }else{
            return ['code'=>1001,'message'=>'请传入公司ID'];
        }
    }
    public function zidianlist(Request $request){
        $zidian = new Dictionary();
        $yewuxian = $zidian->contents("1"); //传入对应的字段值
        $jigouleixing = ['自营','合作','外卖'];
        return ['yewuxian'=>$yewuxian,'jigouleixing'=>$jigouleixing];
    }
    public function sheng(Request $request){
        $sheng = Db::table('region')
                    ->where('code','<>',100000)
                    ->select('code as id','fullName as value','parentCode')
                    ->get();
        $sheng = json_decode(json_encode($sheng),true);
        $res = new Common;
        $data = $res->createTree($sheng,100000,'id','parentCode');
        // foreach ($sheng as $key => $value) {
        //      $shi = Db::table("region")
        //     ->where('parentCode',$value['code'])
        //     ->get()
        //     ->toArray();
        //     $shi = json_decode(json_encode($shi),true);
        //     foreach($shi as $k => $v){
        //         $qu = Db::table("region")
        //             ->where('parentCode',$v['code'])
        //             ->get()
        //             ->toArray();
        //         $qu = json_decode(json_encode($qu),true);
        //     }
        //     $sheng[$key]['shi'] = $shi;
        //     $sheng[$key]['shi']['qu'] = $qu;
        // }
        // print_r($data);exit;
        return ['data'=>$data];
    }
    public function shi(Request $request){
        $shi = Db::table("region")
            ->where('parentCode',$request['shengcode'])
            ->get()
            ->toArray();
        return ['data'=>$shi];
    }
    public function qu(Request $request){
        $qu = Db::table("region")
            ->where('parentCode',$request['shicode'])
            ->get()
            ->toArray();
        return ['data'=>$qu];
    }
    // 修改公司信息
    public function branch_edit(Request $request){
        if($request){
            $data = $request->query();
            if($data['id']){
                $file = $request['file'];//获取个人照片
                if ($file) {
                    $data['pic'] = $file;
                }
                $data['update_user'] = session('uid');
                $data['update_time'] = date('Y-m-d H:i:s',time());
                $save = Db::table('branch')->where('id','=',$data['id'])->update($data);
                $user['head'] = isset($data['contact']) ? $data['contact'] : '';
                $user['sex'] = isset($data['sex'])  ? $data['sex'] : '';
                $user['head_phone'] = isset($data['tel'])  ? $data['tel'] : '';
                $user['qq'] = isset($data['qq']) ? $data['qq'] : '';
                $user['wx'] = isset($data['wx'])  ? $data['wx'] : '';
                $user['business'] = isset($data['business'])  ? $data['business'] : '';
                $user['type'] = isset($data['type'])  ? $data['type'] : '';
                $user['contact'] = isset($data['contact'])  ? $data['contact'] : '';
                $user['contact_phone'] = isset($data['contact_phone'])  ? $data['contact_phone'] : '';
                $user['contact_qq'] = isset($data['contact_qq'])  ? $data['contact_qq'] : '';
                $user['contact_vx'] = isset($data['contact_vx'])  ? $data['contact_vx'] : '';
                $saveuser = Db::table('branch_user')->where('branch_id','=',$data['id'])->update($user);
                if($save && $saveuser){
                    $res = ['code'=>1000,'message'=>'修改成功!'];
                }else{
                    $res = ['code'=>1001,'message'=>'修改失败,没有数据发生变化!'];
                }
            }else{
                $res = ['code'=>1002,'message'=>'修改失败,没有找到符合条件的数据!'];
            }
        }else{
            $res = ['code'=>1003,'message'=>'参数错误!'];
        }
        return $res;
    }

    // 删除公司 软删除
    public function del(Request $request){
    	if($request['id']){
            $id = $request['id'];
            // dd($id);
    		$data['is_delete'] = 2;
    		$data['update_time'] = date('Y-m-d H:i:s',time());
    		$data['update_user'] = session('uid');
            // dd($id);
    		$del = Db::table('branch')->whereIn('id',$id)->update($data);
    		if($del){
    			$res = ['code'=>1000,'message'=>'删除成功!'];
    		}else{
    			$res = ['code'=>1002,'message'=>'删除失败,请确认该数据是否已经删除!'];
    		}
    	}else{
    		$res = ['code'=>1001,'message'=>'未找到要删除的数据!'];
    	}
    	return $res;
    }

    // 关联车队->车队列表
    public function convoylist(Request $request){
    	if($request){
    		// 获取车队
    		$convoy = Db::table('convoy as c')
                ->join('branch as b','b.id','=','c.branch_id','left')
                ->where('c.is_delete','=',1)
                ->select('*','b.id as bid')
    			->get()
                ->toArray();
    		$convoy = json_decode(json_encode($convoy),true);
    		// dump($company_id);exit;
    		
	    	if($convoy){
	    		$res = ['code'=>1000,'message'=>'查询数据成功!','data'=>$convoy];
	    	}else{
	    		$res = ['code'=>1001,'message'=>'没有查找到车队信息!'];
	    	}
    	}else{
    		$res = ['code'=>1002,'message'=>'参数错误!'];
    	}
    	return $res;
    }
    // 车队关联公司
    public function bdconvoy(Request $request){
    	if($request['id']){
    		$data['branch_id'] = $request['id']; //机构/公司 ID
    		$data['save_time'] = date('Y-m-d H:i;s',time());
    		$data['save_userid'] = session('uid');
    			$list = Db::table('convoy')
    			->whereIn('id',$request['convoy_id'])
    			->update($data);
    			if($list){
    				$res = ['code'=>1000,'message'=>'车队关联成功!'];
    			}else{
    				$res = ['code'=>1002,'message'=>'关联失败,请确认该车队是否已经关联到该机构!'];
    			}
    	}else{
    		$res = ['code'=>1001,'message'=>'没有找到符合条件的数据!'];
    	}
        return $res;
    }

    // 添加机构
    public function add(Request $request){
    	if($request){
            if($request['company_name']){
                $data['company_name'] = $request['company_name'];
            }else{
                $data['company_name'] = '';
            }
            if($request['area']){
                $data['area'] = $request['area'];
            }else{
                $data['area'] = '';
            }
            if($request['contact']){
                $data['contact'] = $request['contact'];
            }else{
                $data['contact'] = '';
            }
            if($request['tel']){
                $data['tel'] = $request['tel'];
            }else{
                $data['tel'] = '';
            }
            if($request['business']){
                $data['business'] = $request['business'];
            }else{
                $data['business'] = '';
            }
            if($request['type']){
                $data['type'] = $request['type'];
            }else{
                $data['type'] = '';
            }
            if($request['address']){
                $data['address'] = $request['address'];
            }else{
                $data['address'] = '';
            }
            if($request['contact']){
                $data['contact'] = $request['contact'];
            }else{
                $data['contact'] = '';
            }
            if($request['contact_phone']){
                $data['contact_phone'] = $request['contact_phone'];
            }else{
                $data['contact_phone'] = '';
            }
            if($request['sex']){
                $data['sex'] = $request['sex'];
            }else{
                $data['sex'] = '';
            }
            if($request['head_phone']){
                $data['head_phone'] = $request['head_phone'];
            }else{
                $data['head_phone'] = '';
            }
    		if($request['qq']){
                $data['qq'] = $request['qq'];
            }else{
                $data['qq'] = '';
            }
            if($request['wx']){
                $data['wx'] = $request['wx'];
            }else{
                $data['wx'] = '';
            }
            if($request['contact_qq']){
                $data['contact_qq'] = $request['contact_qq'];
            }else{
                $data['contact_qq'] = '';
            }
            if($request['contact_vx']){
                $data['contact_vx'] = $request['contact_vx'];
            }else{
                $data['contact_vx'] = '';
            }
    		$file = $request['file'];//获取单个照片
            //return $file;
            if ($file) {
                $branchdata['pic'] = $file;
                $userdata['header_pic'] = $file;
            }

    		$branchdata['update_user'] = session('uid');
			$branchdata['update_time'] = date('Y-m-d H:i;s',time());
            $branchdata['is_delete'] = 1;
            $branchdata['company_name'] = $data['company_name'];
            $branchdata['area'] = $data['area'];
            $branchdata['contact'] = $data['contact'];
            $branchdata['tel'] = $data['tel'];
            $branchdata['business'] = $data['business'];
            $branchdata['type'] = $data['type'];
            $branchdata['address'] = $data['address'];
            $userdata['head'] = $data['contact'];
            $userdata['sex'] = $data['sex'];
            $userdata['head_phone'] = $data['head_phone'];
            $userdata['qq'] = $data['qq'];
            $userdata['wx'] = $data['wx'];
            $userdata['business'] = $data['business'];
            $userdata['type'] = $data['type'];
            $userdata['contact'] = $data['contact'];
            $userdata['contact_phone'] = $data['contact_phone'];
            $userdata['contact_qq'] = $data['contact_qq'];
            $userdata['contact_vx'] = $data['contact_vx'];
			$userdata['is_delete'] = 1;
            $userdata['create_time'] = date('Y-m-d H:i;s',time());
            $branchadd = Db::table('branch')->insertGetId($branchdata);
            $userdata['branch_id'] = $branchadd;
    		$useradd = Db::table('branch_user')->insert($userdata);
    		if($useradd){
    			$res = ['code'=>1000,'message'=>'机构增加成功!'];
    		}else{
    			$res = ['code'=>1001,'message'=>'机构增加失败,请刷新后重试!'];
    		}
    	}else{
    		$res = ['code'=>1003,'message'=>'参数错误!'];
    	}
    	return $res;
    }
    // 机构详情页面
    public function branchitem(Request $request){
        if($request['id']){
            // 机构详情
            $data = Db::table('branch as b')
                ->join('branch_user as c','c.branch_id','=','b.id','left')
                ->join('user as u','u.id','=','b.update_user','left')
                ->where('b.id',$request['id'])
                ->select('b.*','c.head','c.head_phone','c.qq','c.wx','c.contact','c.contact_phone','c.contact_qq','c.contact_vx','u.name','u.id as uid')
                ->first();
            $data = json_decode(json_encode($data),true);
            if($data){
                $res = ['code'=>1000,'message'=>'获取数据成功','data'=>$data];
            }else{
                $res = ['code'=>1001,'message'=>'没有找到符合条件的数据','data'=>$data];
            }
        }else{
            $res = ['code'=>1002,'message'=>'获取数据失败,请传入机构ID'];
        }
        return $res;
    }
    // 详情页绑定车队列表
    public function itemconvoylist(Request $request){
        if($request['id']){
            $list = Db::table('convoy as c')
                ->join('driver as d','d.convoy_id','=','c.id','left')
                // ->join('driver as e','c.id','=','e.convoy_id','left')
                ->join('user as u','c.save_userid','=','u.id','left')
                // ->join('car_car as f','c.id','=','f.teamid','left')
                ->where('c.branch_id',$request['id'])
                ->select('c.*','d.driver_phone','c.id as cid','d.convoy_id','d.driver_name as dzname','u.name as username',DB::raw("COUNT(convoy_id) as drivercount,COUNT(car_id) as carcount"))
                ->groupBy("c.id")
                ->get()
                ->toArray();
            $list = json_decode(json_encode($list),true);
            if($list){
                $res = ['code'=>1000,'message'=>'获取数据成功','data'=>$list];
            }else{
                $res = ['code'=>1001,'message'=>'没有找到符合条件的数据','data'=>$list];
            }
        }else{
            $res = ['code'=>1002,'message'=>'获取数据失败,请传入机构ID'];
        }
        return $res;
    }
    // 解除绑定的车队
    public function convoyjiechu(Request $request){
        // 判断是否传输过来机构ID以及绑定车队ID
        if($request['convoy_id']){
            $data['branch_id'] = '';
            $data['save_userid'] = session('uid');
            $data['save_time'] = date('Y-m-d H:i;s',time());
            $save = Db::table('convoy')
                ->where('id',$request['convoy_id'])
                ->update($data);
            if($save){
                $res = ['code'=>1000,'message'=>'车队解绑成功'];
            }else{
                $res = ['code'=>1001,'message'=>'车队解绑失败,请确认该车队是否已经关联到该机构'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'获取数据失败,请传入车队ID'];
        }
        return $res;
    }
}
